// pages/subpackage/TheTripInitiated/index.js
//首页点击进来的乘客的详情页  感觉这个还是要弃用

var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    updateTit: ['预约中', '预约中', '已满', '已出发', '已结束', '已预支付'],
    typePrice: '1',
    PriceShow: false,
    PriceListShow: false,
    negotiatePriceList: [],
    PrePrice: '',
    StatusBar: 20,
    show: false,
    columns: [],
    seat: 1,
    PreSeat: 1,
    message: '',
    Moditit: '手机号修改',
    Modishow: false,
    messageModi: '',
    price: '',
    Preprice: '',
    TravelInformation: {},
    AjaxData: {},
    phoneNumber: '',
    plateNumber: '',
    isUser: false,
    id: '',
    amountTo: 0,
    isgetIinformation: false,
    getShow: false,
    showPrivacy: false,
    serviceCharge: 0,
    ReleasePayment: false,
    shareObj: {},
    payShow: false,
    OwnerIssuedbot: 180,
    startY: 0, // 记录手指按下的初始位置
    currentY: 430, // 记录当前的位置
    isShare: false,
    // tenxunKey: 'THYBZ-MKP6T-XPNXQ-LWAAV-5FOCV-E5FVZ',//贰加科技key码
    tenxunKey: 'DXMBZ-OMZLA-SA6KM-CXRT4-O5MJ3-TVBHJ',//第三方key码
    polyline: [],
    longitude: 0,
    latitude: 0,
    markers: [],
    customCalloutMarkerIds: [],
    distance: 0,
    duration: 0,
    scale: 9,
    WhetherAPrice: '1',
    TotalServiceFee: 0,
    intervalId: null,
    orderReceivingShow: false,
    farePrice: '', // 车主接单后填入的车费
    fareSeat: 1, // 车主接单后填入的人数
    goods_id: '', // 接口后的行程详情id
    NewRelease: false,
    ShareCardShow: false,
    Sharing: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("=========================进入passengerTravel===============首页点击进来的乘客的详情页======");
    let that = this
    let data = ''
    if (app.globalData.position) {
      this.setData({
        longitude: app.globalData.position.longitude,
        latitude: app.globalData.position.latitude
      })
    }
    try {
      const scene = decodeURIComponent(options.scene)
      if (options.isShare || scene != 'undefined') {
        this.setData({
          isShare: true
        })
      }
      if (options.Showshare) {
        this.setData({
          NewRelease: true
        })
      }
      if (options.id || scene != 'undefined') {
        const systemInfo = wx.getSystemInfoSync();
        const screenHeight = systemInfo.windowHeight;
        let number = ''
        if (scene) {
          let index = scene.indexOf('&'); // 找到 & 的位置
          number = scene.substring(3, index); // 获取 & 前面的数字部分
        }
        this.setData({
          id: options.id?options.id: number,
          isUser: true,
          detailsId: options.detailsId
          // currentY: screenHeight - 150
        })
        this.getDetailsshare()
      }else {
        data = JSON.parse(options.data)
      }
      let columns = []
      for (let index = 1; index < 11; index++) {
        columns.push(index)
      }
      this.setData({
        columns,
        TravelInformation: data,
        StatusBar: app.globalData.StatusBar
      })
    } catch (error) {
      console.log(error);
    }
  },
  PreSelectedSeats (e) {
    let seat = e.currentTarget.dataset.index + 1
    this.setData({
      PreSeat: seat
    })
  },
  // 议价选择
  PreSelectedPrices (e) {
    let seat = e.currentTarget.dataset.index
    this.setData({
      PrePrice: seat
    })
  },
  onConfirm() {
    if (this.data.TravelInformation.role !== 3) {
      this.setData({
        fareSeat: this.data.PreSeat,
        show: false
      })
      return
    }
    let that = this
    let PreSeat = this.data.PreSeat
    let data = {
      id: this.data.id,
      seat: PreSeat
    }
    util.request('POST', api.postSeatEsc, data).then(function (res) {
      console.log(res);
      if (res.code == 200) {
        wx.showToast({
          title: '修改成功！',
        })
        that.ResettheAcquisition()
      }else {
        wx.showToast({
          title: '修改失败 请稍后再试！',
          icon: 'none'
        })
      }
      that.setData({
        show: false
      })
    })
  },
  // 车主继续接单
  onOredrConfirm () {
    let plateNumber = this.data.plateNumber
    let phoneNumber = this.data.phoneNumber
    let fareSeat = this.data.fareSeat
    let farePrice = this.data.farePrice

    if (!plateNumber || !phoneNumber || !farePrice) {
      wx.showToast({
        title: '请完善信息',
        icon: 'none'
      })
      return
    }
    let that = this
    let data = {
      "phone": phoneNumber,
      "goods_id": that.data.id, // 行程ID
      "plateNumber" : plateNumber,
      "seat": fareSeat, //座位
      "price": farePrice //车费
    }
    util.request('POST', api.postInvitationCon, data).then(function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: '继续接单成功',
          icon: 'none'
        })
        let timer = setTimeout(() => {
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + that.data.id + '&role=1',
          })
          clearTimeout(timer)
        }, 1000)
      }else {
        wx.showToast({
          title: '继续接单失败~',
          icon: 'none'
        })
        let timer = setTimeout(() => {
          wx.navigateBack()
          clearTimeout(timer)
        }, 1000)
      }
    }).catch((res) => {
      wx.hideLoading()
    })
  },
  onPriceClose () {
    if (this.data.typePrice !== '1' || this.data.TravelInformation.role == 3) {
      return
    }
    this.negotiatePrice()
    this.setData({
      PriceShow: !this.data.PriceShow
    })
  },
  onPriceConfirm () {
    let that = this
    let data = {
      "id": this.data.id,//行程ID
      "phone": wx.getStorageSync('TwoPlusTravel').phone,//用户手机号
      "money": parseFloat(this.data.PrePrice), //金额
      "seat": this.data.seat
    }
    util.request('POST', api.postOwnerBargaining, data).then(function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        wx.showToast({
          title: '已提交协商价格 请等候乘客回复',
          icon: 'none'
        })
        that.ResettheAcquisition()
      }else {
        wx.showToast({
          title: '协商价格提交失败 请稍后再试',
          icon: 'none'
        })
      }
    }).catch((res) => {
      wx.hideLoading()
    })
    this.setData({
      PriceShow: false
    })
  },
  onClose () {
    this.setData({
      show: false,
      Modishow: false
    })
  },
  payClose () {
    console.log(11);
    this.setData({
      payShow: false,
      ReleasePayment: false
    })
  },
  TheSeatFilled () {
    this.setData({
      show: true
    })
  },
  onChange (e) {
    this.setData({
      message: e.detail
    })
  },
  WhetherAPriceChange (e) {
    this.setData({
      WhetherAPrice: e.detail
    })
  },
  onModiChange (e) {
    this.setData({
      messageModi: e.detail
    })
  },
  reviseModiBtn (e) {
    let tit = e.currentTarget.dataset.tit
    if (tit == '手机号修改') {
      this.setData({
        messageModi: this.data.phoneNumber
      })
    }else if (tit == '车牌号修改') {
      this.setData({
        messageModi: this.data.plateNumber
      })
    }else {
      this.setData({
        messageModi: this.data.farePrice
      })
    }
    this.setData({
      Moditit: tit,
      Modishow: true
    })
  },
  affirmBtn () {
    let timer = setTimeout(() => {
      let messageModi = this.data.messageModi
        if (messageModi == '') {
          wx.showToast({
            title: '请输入内容',
            icon: 'none'
          })
          return
        }
        let Moditit = this.data.Moditit
        if (Moditit == '手机号修改') {
          var regex = /^1[3-9]\d{9}$/;
          if (!regex.test(messageModi)) {
            wx.showToast({
              title: '手机号码格式有误',
              icon: 'none'
            })
            return
          }
          this.setData({
            phoneNumber: messageModi,
          })
        }else if (Moditit == '车牌号修改') {
          if (!util.isValidChineseLicensePlate(messageModi)) {
            wx.showToast({
              title: '车牌号格式有误',
              icon: 'none'
            })
            return
          }
          wx.setStorageSync('TwoPlusTravel-plateNumber', messageModi)
          this.setData({
            plateNumber: messageModi,
          })
        }else {
          if (Number(messageModi) == 0) {
            wx.showToast({
              title: '请输入',
              icon: 'none'
            })
            return
          }
          this.setData({
            farePrice: messageModi,
          })
        }
        this.setData({
          Modishow: false,
          messageModi: ''
        })
        clearTimeout(timer)
    }, 100)
  },
  priceonChange (e) {
    this.setData({
      price: e.detail
    })
  },
  setNum() {
    if (this.data.Moditit != '价格修改') {
      return
    }
    let obj = this.data.messageModi
    if (obj == '') {
      return
    }
    //替换掉数字和小数点 . 之外的字符
    obj = obj.replace(/[^\d.]/g,"");
    //把2个以上的小数点 . 替换成一个小数点 . 
    obj = obj.replace(/\.{2,}/g,".");
    //保证第一个字符为数字而不是小数点 .
    obj = obj.replace(/^\./g,"");
    //保证最后一个字符为数字而不是小数点 .
    obj = obj.replace(/\.$/g,"");
    //保证小数点 . 只出现一次，而不能出现两次以上
    obj = obj.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
    //只能输入两个小数
    obj = obj.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');
    obj = Number(obj).toFixed(2)
    this.setData({
      messageModi: obj
    })
  },
  cancel () {
    this.setData({
      showPrivacy: false
    })
  },
  PlatformRulesPrompt () {
    let that = this
    let isempower = wx.getStorageSync('empower') || ''
    // 是否同意协议
    if (isempower) {
      wx.showLoading({
        title: '正在发布中~'
      })
      that.TravelRelease()
    }else {
      that.setData({
        showPrivacy: true
      })
    }
  },
  TravelRelease () {
    if (this.data.ReleasePayment) {
      return
    }
    let that = this
    this.setData({
      showPrivacy: false,
      ReleasePayment: true
    })
    wx.setStorageSync('empower', true)
    let price = this.data.price
    if (!price && !this.data.plateNumber && !this.data.phoneNumber) {
      return
    }
    // 用户支付
    wx.hideLoading()
    that.setData({
      payShow: true,
      ReleasePayment: false
    })
    return
  },
  // 用户支付
  UserItineraryPayment () {
    if (this.data.ReleasePayment) {
      return
    }
    
    let that = this
    that.setData({
      ReleasePayment: true
    })
    let datas = {
      id: this.data.id,
      phone: wx.getStorageSync('TwoPlusTravel').phone, // 用户电话
      telephone: this.data.phoneNumber, // 乘车人电话
      seat: this.data.seat, // 座位
      price: this.data.amountTo, // 车费
      hjmoney: this.data.AjaxData.money,
      open_id: wx.getStorageSync('TwoPlusTravel').openid,
      service_charge:this.data.AjaxData.service_charge, // 服务费
    }
    util.request('POST', api.postWeChatPay, datas).then(function (res) {
      if (res.code == 101 || res.code == '101') {
        wx.hideLoading()
        wx.showToast({
          title: '该行程已存在 请勿重复支付',
          icon: 'none'
        })
        return
      }
      if (res.code == 105) {
        wx.hideLoading()
        wx.showToast({
          title: '支付金额不匹配,支付失败',
          icon: 'none'
        })
        that.setData({
          ReleasePayment: false
        })
        return
      }
      if (Object.keys(res).length) {
        let payParam = res
        wx.hideLoading()
        wx.requestPayment({
          timeStamp: payParam.timeStamp,
          nonceStr: payParam.nonceStr,
          package: payParam.package,
          signType: payParam.signType,
          paySign: payParam.paySign,
          success (res) { 
            wx.showToast({
              title: '支付成功。',
            })
            that.setData({
              payShow: false
            })
            that.ResettheAcquisition()
          },
          fail (res) {
            console.log(res);
            wx.showToast({
              title: '支付失败 已取消支付！',
              icon: 'none',
              duration: 2000
            })
            that.setData({
              ReleasePayment: false
            })
           }
        })
      }else {
        that.setData({
          ReleasePayment: false
        })
      }
    })
  },
  getstyle () {
    return false
    // plateNumber && phoneNumber && (fareSeat > seat? farePrice: '')
  },
//   调用动态数据
getCshiUrl () {
    let that = this
    let phone = wx.getStorageSync('TwoPlusTravel').phone || ''
    if(this.data.TravelInformation.role == 5){
      var url = api.csUrl
    }else{
    //   var url = api.carUrlAjax
        var url = api.myPassengerUrlAjax
    }
    util.request('GET', url, {id: this.data.id,phone: phone,details_id:this.data.TravelInformation.details_id,role:this.data.TravelInformation.role}).then(function(res)  {
        if(res.orderState == 2){
            clearInterval(that.data.intervalId);
            that.setData({
              intervalId: null
            })
            wx.showToast({
              title: '已通过议价',
              duration: 1000
            })
            let time = setTimeout(() => {
              wx.navigateTo({
                url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + that.data.id + '&role=1',
              })
              clearTimeout(time)
            }, 1000)
            return
        }
        if(res.typePriceArr == 9){
           //    判断行程不存在，跳转至首页
           clearInterval(that.data.intervalId)
           that.setData({
             intervalId: null
           })
           wx.showToast({
             title: '行程不存在',
             duration: 1000,
             success: function () {
               setTimeout(function () {
                 wx.reLaunch({
                   url: '/pages/index/index',
                 })
               }, 1000);
            }
          })
          return
      }
        let amountTo = parseFloat(res.money) + parseFloat(res.service_charge)
        that.setData({
          AjaxData: res,
          amountTo: amountTo.toFixed(2),
          TotalServiceFee: res.service_charge
        })
    },(err) => {
        console.log('请求出错了')
    })
    
},
  // 获取行程信息
  getDetailsTrip () {
    let that = this
    let phone = wx.getStorageSync('TwoPlusTravel').phone || ''
   debugger
    const reqJsonDatw = {
        id: this.data.id,
        phone: phone,
        details_id:that.data.detailsId
    }
    console.log(reqJsonDatw)
    // util.request('GET', api.carDetailsTrip, {id: this.data.id,phone: phone,role:this.data.role}).then(function (res) {
    // util.request('GET', api.Passenger, {id: this.data.id,phone: phone}).then(function (res) {  
    util.request('GET', api.detailsOrder, reqJsonDatw).then(function (res) {  
        console.log("首页点击进来的乘客的详情页")
        console.log(res)
        console.log("首页点击进来的乘客的详情页")
    try {
        // "state":   1 不可预约 2 可预约 3乘客已确定订单 4 乘客已经上车
        if (res.state == 1) {
          wx.showToast({
            title: '行程已满/不可预约',
            icon: 'none'
          })
          let time = setTimeout(() => {
            wx.reLaunch({
              url: '/pages/index/index'
            })
            clearTimeout(time)
          }, 800)
          return
        }
        if (res.state == 3 || res.state == 4 || res.role == 1) {
          wx.showToast({
            title: '跳转至行程页',
            icon: 'none'
          })
          let times = setTimeout(() => {
            wx.reLaunch({
              url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + res.id + '&role=' + res.role,
            })
            clearTimeout(times)
          }, 800)
          return
        }
        // debugger
        if (res) {
          // let num = parseFloat(res.price)*that.data.seat
          let num = parseFloat(res.price)
          if (res.details_number != undefined) {
            num = num + Number(res.details_number)
          }
          let columns = []
          for (let index = 1; index < res.seat + 1; index++) {
            columns.push(index)
          }
          res.godate= util.timeChangeover(res.godate)
          if (!res.PriceData || !res.PriceData.length) {
            that.setData({
              PriceListShow: false
            })
          }
          that.setData({
            // fareSeat: that.data.fareSeat > res.seat?that.data.fareSeat: res.seat + 1,
            seat: res.seat,
            // PreSeat: that.data.PreSeat > res.seat?that.data.PreSeat: res.seat,
            TravelInformation: res,
            AjaxData:res,
            TotalServiceFee: res.details_number?parseFloat(res.details_number).toFixed(2): 0,
            message: res.kindlyReminder,
            amountTo: res.money,
            price: parseFloat(res.price).toFixed(2),
            columns: columns,
            serviceCharge: res.details_number?parseFloat(res.details_number).toFixed(2): 0
          })
          that.getCshiUrl()
          that.negotiatePrice()
          if (!that.data.customCalloutMarkerIds.length) {
            that.buttonDriving()
          }
        }
      } catch (error) {
        
      }
      
    })
  },
  // 议价弹窗价格列表
  negotiatePrice () {
    let list = []
    let firlist = []
    let startingNumber = parseFloat(this.data.AjaxData.money)
    if (startingNumber <= 10) {
      list.push(startingNumber)
    }

    let currentNumber = startingNumber;
    let fircurrentNumber = startingNumber;

    let index = 1
    let firindex = 1

    // while (currentNumber > 10 && index < 50) {
    //   let num = parseFloat(currentNumber).toFixed(2)
    //   list.push(num)
    //   index++;
    //   currentNumber -= 10;
    // }
    while (firindex < 50) {
      let fnum = parseFloat(fircurrentNumber)
      firlist.push(fnum)
      firindex++;
      let result = ((fircurrentNumber * 100 + 1000) / 100);
      fircurrentNumber = result;
    }
    // firlist = firlist.reverse()

    this.setData({
      negotiatePriceList: firlist,
      PrePrice: this.data.PrePrice == ''?startingNumber: this.data.PrePrice
    })
  },
  // 登录授权
  getUserInfo: function (e) {
    var that = this ;
    that.setData({
      isgetIinformation: true
    })
    wx.showLoading({
      title: '正在获取中...',
    })
    var detail = e.detail
    if (detail.errMsg == "getPhoneNumber:ok") {
      var code = detail.code
      util.request('POST', api.Login, {
        code: code
      }).then(function (res) {
        if (res.code == 200) {
          let token = res.data
          wx.login({
            success (res) {
              if (res.code) {
                util.request('POST', api.getopenid, {
                  code: res.code
                }).then(function (res) {
                  if (res.openid) {
                    wx.setStorageSync('TwoPlusTravel', {openid: res.openid, session_key: res.session_key, phone: token})
                    wx.hideLoading()
                    that.setData({
                      phoneNumber: token,
                      getShow: false,
                      isgetIinformation: false
                    })
                    if (!Object.keys(that.data.TravelInformation).length) {
                      that.ResettheAcquisition()
                    }
                    wx.showToast({
                      title: '获取成功！',
                      icon: 'success'
                    })
                  }else {
                    wx.hideLoading()
                    wx.showToast({
                      title: '获取失败 请重试~',
                      icon: 'error'
                    })
                    that.setData({
                      isgetIinformation: false
                    })
                  }
                }).catch((res) => {
                  wx.hideLoading()
                  wx.showToast({
                    title: '获取失败 请重试~',
                    icon: 'error'
                  })
                  that.setData({
                    isgetIinformation: false
                  })
                })
              } else {
                wx.hideLoading()
                wx.showToast({
                  title: '获取失败 请重试~',
                  icon: 'error'
                })
                that.setData({
                  isgetIinformation: false
                })
              }
            }
          })
        }
      }).catch((res) => {
        wx.hideLoading()
        wx.showToast({
          title: '获取失败 请重试~',
          icon: 'error'
        })
        that.setData({
          isgetIinformation: false
        })
      })
    }else {
      wx.hideLoading()
      wx.showToast({
        title: '获取失败 请重试~',
        icon: 'error'
      })
      that.setData({
        isgetIinformation: false
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.Sharing) {
      this.setData({
        ShareCardShow: false
      })
    }
    // 手机号
    let TwoPlusTravel = wx.getStorageSync('TwoPlusTravel')
    if (this.data.id) {
      if (TwoPlusTravel.phone) {
        // this.getpaymentDetermine(this.data.id)
        this.ResettheAcquisition()
      }else {
        wx.showToast({
          title: '未登录 前往登录中~',
          icon: 'none',
          duration: 1500
        })
        let time = setTimeout(() => {
          wx.navigateTo({
            url: '/pages/subpackage/wxlogin/index'
          })
          clearTimeout(time)
        }, 1500)
      }
    }
    
    if (TwoPlusTravel) {
      this.setData({
        phoneNumber: wx.getStorageSync('TwoPlusTravel').phone
      })
    }else {
      this.setData({
        phoneNumber: ''
      })
    }
    // 车牌号
    let TwoPlusTravelPlateNumber = wx.getStorageSync('TwoPlusTravel-plateNumber')
    if (TwoPlusTravelPlateNumber) {
      this.setData({
        plateNumber: TwoPlusTravelPlateNumber
      })
    }else {
      this.setData({
        plateNumber: ''
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.intervalId);
    this.setData({
      intervalId: null
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },
  // 获取分享
  getDetailsshare () {
    let that = this
    util.request('GET', api.getDetailsPeopleShare, {id: this.data.id}).then(function (res) {
    //   debugger
      console.log(res);
      if (Object.keys(res).length) {
        that.setData({
          shareObj: res
        })
        if (that.data.NewRelease && !that.data.Sharing) {
          that.setData({
            ShareCardShow: true
          })
        }
      }
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    if (this.data.isUser) {
      debugger
      let shareObj = this.data.shareObj
      var title = `人找车 ${shareObj.setAddress}-${shareObj.reachAddress}`   // 标题
      let id = this.data.id
      let detailsId = this.data.detailsId
      return {
        title: title,
        imageUrl: shareObj.image_url,
        path: `/pages/subpackage/DetailsPassengerTravel/index?id=${id}&isShare=1&detailsId=${detailsId}`
      }
    }
  },
  handleTouchStart: function (event) {
    // 记录手指按下的初始位置
    this.setData({
      startY: event.touches[0].clientY // 记录触摸开始时的Y坐标
    });
  },

  handleTouchMove: function (event) {
    const moveY = event.touches[0].clientY; // 当前触摸点的Y坐标
    const deltaY = moveY - this.data.startY; // 计算移动的距离
    console.log(moveY);
    if (moveY < 120 || moveY > 450) {
      return
    }
    this.setData({
      currentY: this.data.currentY - deltaY // 更新currentY值
    });
    this.setData({
      startY: moveY // 更新startY为当前Y坐标
    });
  },
  gotoback () {
    clearInterval(this.data.intervalId)
    this.setData({
      intervalId: null
    })
    // 获取页面栈
    const pages = getCurrentPages();
    // 上一层页面是页面栈的倒数第二个
    const prevPage = pages[pages.length - 2];
    // 如果上一层页面存在，则可以返回
    if (prevPage && prevPage.route != 'pages/subpackage/PassengerRelease/index') {
      wx.navigateBack();
    } else {
      // 没有上一层页面的处理逻辑
      wx.reLaunch({
        url: '/pages/index/index'
      })
    }
  },
  // 获取路线
  buttonDriving () {
    wx.showLoading({
      title: '加载中',
    })
    let TravelInformation = this.data.TravelInformation
    let to = {
      latitude: TravelInformation.alatitude,
      longitude: TravelInformation.alongitude
    }
    let from = {
      latitude: TravelInformation.platitude,
      longitude: TravelInformation.plongitude
    }
    var _this = this
    wx.request({
      url: `https://apis.map.qq.com/ws/direction/v1/driving/?key=${this.data.tenxunKey}&from=${from.latitude},${from.longitude}&to=${to.latitude},${to.longitude}`,
      success(res){
        console.log(res);
        if (res.data.status !== 0) {
          wx.hideLoading()
          wx.showToast({
            title: res.data.message,
            icon:'none'
          })
          return
        }
        var result = res.data.result
        var route = result.routes[0]
        
        var coors = route.polyline, pl = [];
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        var kr = 1000000;
        for (var i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
        }
        //将解压后的坐标放入点串数组pl中
        for (var i = 0; i < coors.length; i += 2) {
          pl.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        
        wx.hideLoading()
        _this.setData({
          // 将路线的起点设置为地图中心点
          latitude:pl[0].latitude,
          longitude:pl[0].longitude,
          // 绘制路线
          polyline: [{
            points: pl,
            color: '#1bc3a9',
            width: 6,
            borderColor: '#2ca28d',
            borderWidth: 1,
            arrowLine: true
          }]
        })
        // 标点
        let distance = (route.distance / 1000).toFixed(2); // 总路线公里
        let duration = _this.HoursAndMinutes(route.duration) // 路线约分钟
        let ListMerchants = []
        let customCalloutMarkerIds = [
          {
            id: 0,
            distance: distance,
            duration: duration
          }
        ]
        for (let index = 0; index < 2; index++) {
          let items = {
            id: index,
            title: index? TravelInformation.reachAddress: TravelInformation.setAddress,
            latitude: index?Number(TravelInformation.alatitude):Number(TravelInformation.platitude),
            longitude: index?Number(TravelInformation.alongitude):Number(TravelInformation.plongitude),
            width: '20',
            height: '30',
            iconPath: index?'/images/terminalPoint.png':  '/images/startingPoint.png',
          }
          if (index == 0) {
            items.customCallout = {
              anchorY: -5,
              anchorX: 0,
              display: 'ALWAYS',
            }
          }
          ListMerchants.push(items)
        }
        _this.setData({
          distance,
          duration,
          markers: ListMerchants,
          customCalloutMarkerIds: customCalloutMarkerIds
        })
      }
    })
  },
  // 授权获取地理位置
  getLocation () {
    let that = this
    wx.getLocation({
      type: 'gcj02', //表示使用GPS定位
      success: (res) => {
        app.globalData.position.latitude = res.latitude;
        app.globalData.position.longitude = res.longitude;
        that.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
      },
      //表示用户没有开启授权
      fail: (res) => {
        wx.showToast({
          title: '已取消定位,授权定位服务',
          icon: 'none'
        })
        let timer = setTimeout(() => {
          wx.showModal({
            title: '',
            confirmColor: '#b4282d',
            content: '需要获取地理位置 请确认授权',
            success: function (res) {
              if (res.confirm) {
                wx.openSetting({
                  success (res) {
                    if (!res.authSetting['scope.userLocation']) {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'error'
                      })
                    }
                  },
                  fail (res) {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'error'
                    })
                  }
                })
              }
            }
          })
          clearTimeout(timer)
        }, 1000)
      }
    })
  },
  HoursAndMinutes(minutes) {
    // 计算小时数
    const hours = Math.floor(minutes / 60);
    // 计算剩余分钟数
    const remainingMinutes = minutes % 60;

    // 如果剩余分钟数为0且小时数大于0，则显示为1小时
    if (remainingMinutes === 0 && hours > 0) {
        return `${hours}小时`;
    }
    // 返回结果
    if (hours == 0) {
      return `${remainingMinutes}分钟`;
    }

    return `${hours}小时${remainingMinutes}分钟`;
  },
  // 调起手机拨号
  dialANumber (e) {
    let num = e.currentTarget.dataset.num
    wx.makePhoneCall({
      phoneNumber: num
    })
  },
  TotalServiceFee () {
    let charge = this.data.TravelInformation.charge
    let seat = this.data.seat
    this.setData({
      TotalServiceFee: charge?parseFloat(charge * seat).toFixed(2): 0
    })
  },
  onPriceShow () {
    // 乘客 同意-驳回 司机议价弹窗
    if (this.data.TravelInformation.role == 3 && this.data.TravelInformation.typePrice != 1) {
      this.setData({
        PriceListShow: !this.data.PriceListShow
      })
    }else {
      // 司机议价列表
      this.negotiatePrice()
      this.setData({
        PriceShow: !this.data.PriceShow
      })
    }
  },
  // 驳回
  bargainingReject (e) {
    let item = e.currentTarget.dataset.index
    let data = {
      id: item.id,
      phone: wx.getStorageSync('TwoPlusTravel').phone
    }
    let lastFourDigits = item.phone.slice(-4)
    let that = this
    wx.showModal({
      title: '提示',
      content: `驳回尾号${lastFourDigits}的议价申请`,
      success (res) {
        if (res.confirm) {
          util.request('POST', api.postBargainingReject, data).then(function (res) {
            if (res.code == 200) {
              wx.showToast({
                title: `尾号${lastFourDigits}议价已驳回`,
                icon: 'none'
              })
              that.ResettheAcquisition()
            }else {
              wx.showToast({
                title: '操作失败 请稍后再试！',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
  // 同意
  bargainingAgree (e) {
    let item = e.currentTarget.dataset.index
    let data = {
      id: item.id,
      phone: wx.getStorageSync('TwoPlusTravel').phone
    }
    let lastFourDigits = item.phone.slice(-4)
    let that = this
    wx.showModal({
      title: '提示',
      content: `同意尾号${lastFourDigits}的议价申请`,
      success (res) {
        if (res.confirm) {
          util.request('POST', api.postBargainingAgree, data).then(function (res) {
            if (res.code == 200) {
              wx.showToast({
                title: `尾号${lastFourDigits}议价已同意`,
                icon: 'none'
              })
              that.ResettheAcquisition()
            }else {
              wx.showToast({
                title: '操作失败 请稍后再试！',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
//   ResettheAcquisition () {
//     this.getDetailsTrip()
//     clearInterval(this.data.intervalId)
//     // this.setData({
//     //   intervalId: setInterval(() => {
//     //     this.getDetailsTrip()
//     //   }, 10000)
//     // })
//   },
  ResettheAcquisition () {
    this.getDetailsTrip()
    clearInterval(this.data.intervalId)
    this.setData({
      intervalId: setInterval(() => {
        // if(this.data.TravelInformation.role == 5 && this.data.AjaxData.orderState == 3){
        //     this.getDetailsTrip()
        //     return
        // }
        this.getCshiUrl()
      }, 10000)
    })
  },
  
  
  orderReceiving () {
    let that = this
    wx.showModal({
      title: `该行程需提供${that.data.TravelInformation.seat}个座位`,
      content: '是否确认接取该行程？',
      complete: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '接单中~'
          })
          let data = {
            "id": that.data.TravelInformation.details_id,
            "phone": that.data.phoneNumber
          }
          util.request('POST', api.postInvitation, data).then(function (ares) {
            wx.hideLoading()
            if (ares.code == 200) {
              wx.showToast({
                title: '接单成功',
                icon: 'none'
              })
              clearInterval(that.data.intervalId);
              that.setData({
                intervalId: null,
                goods_id: ares.goods_id
              })
              that.ContinueToReceiveOrders(ares)
            }else {
              wx.showToast({
                title: '接单失败',
                icon: 'none'
              })
              let timer = setTimeout(() => {
                wx.navigateBack()
                clearTimeout(timer)
              }, 1000)
            }
          }).catch((res) => {
            wx.hideLoading()
          })
        }
      }
    })
  },
  CancelTheOrder () {
    let that = this
    wx.showModal({
      title: '取消继续接单',
      content: '是否确认取消继续接单？',
      complete: (res) => {
        if (res.confirm) {
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + that.data.id + '&role=1',
          })
        }
      }
    })
  },
  ContinueToReceiveOrders(res) {
    let that = this
    wx.showModal({
      title: '是否继续接单',
      content: '以此行程进行发布？',
      complete: (mres) => {
        console.log(mres);
        if (mres.cancel) {
          console.log('cancel');
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + res.goods_id + '&role=1',
          })
        }
        if (mres.confirm) {
          console.log('confirm');
          let orderReceivingShow = !that.data.orderReceivingShow
          that.setData({
            orderReceivingShow,
            plateNumber: res.plateNumber
          })
        }
      }
    })
  },
  TheTripCancelled () {
    let that = this
    wx.showModal({
      title: '提示',
      content: `是否确认取消行程？`,
      success (res) {
        if (res.confirm) {
          let data = {
            "id": that.data.TravelInformation.details_id,// 订单id
            "phone": wx.getStorageSync('TwoPlusTravel').phone // 行程用户
          }
          util.request('POST', api.postcancelPassenger, data).then(function (res) {
            if (res.code == 200) {
              wx.showToast({
                title: `取消成功`,
                icon: 'none'
              })
              clearInterval(that.data.intervalId);
              that.setData({
                intervalId: null
              })
              let time = setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/index/index?passenger=1'
                })
                clearTimeout(time)
              }, 1500);
            } else if (res.code == 103){
              clearInterval(that.data.intervalId);
              that.setData({
                intervalId: null
              })
              wx.showToast({
                title: `取消成功！`,
                icon: 'none'
              })
              let time = setTimeout(() => {
                wx.reLaunch({
                  url: '/pages/index/index'
                })
                clearTimeout(time)
              }, 1500);
            } else {
              wx.showToast({
                title: '操作失败 请稍后再试！',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
  // 获取通过协商 待支付参数
  getpaymentDetermine (id) {
    let that = this
    let data = {
      id,
      phone: wx.getStorageSync('TwoPlusTravel').phone
    }
    try {
      util.request('POST', api.getpaymentDetermine, data).then(function (res) {
        console.log(res);
        if (res.code == 200) {
          let newPrice = Number(res.sumMoney)/Number(res.number)
          let unpaid = res
          unpaid.seat = Number(res.number)
          unpaid.price = Number(res.price)
          unpaid.newPrice = newPrice.toFixed(2)
          that.setData({
            unpaid,
            nowUnpaid: true
          })
          that.ResettheAcquisition()
        }else if (res.code == 300) {
          wx.navigateTo({
            url: '/pages/subpackage/DetailsOfTheTrip/index?id=' + id + '&role=0'
          })
        }else {
          that.setData({
            nowUnpaid: false
          })
          that.ResettheAcquisition()
        }
      })
    } catch (error) {
      that.setData({
        nowUnpaid: false
      })
      that.ResettheAcquisition()
    }
  },
  ShareCardShowClose () {
    this.setData({
      ShareCardShow: false
    })
  },
  InTheSharing () {
    this.setData({
      Sharing: true
    })
  }
})